<?php
namespace Modules\Home\Controllers;

use Modules\Home\Services\UserWalletService;
use Modules\Home\Services\UserAchievementService;
use Modules\Home\Services\UserAchievementLogService;
use Modules\Home\Services\UserWalletGoodsLogService;

class FinanceController extends ControllerBase {
  public function initialize() {
    parent::initialize();

    $this -> _checkLogin();
    $this -> view -> setLayout('index');
  }

  public function indexAction() {
    $this -> tag -> prependTitle('财务中心');

    $user = $this -> session -> get('user');

    $resUserWallet = $this -> user::getWalletServiceInstance() -> findFirst(['user_id = ' . $user['user_id']]);
    if($resUserWallet['code'] != 0) { return $this -> _returnScript($resUserWallet['message']); }

    $resUserAchievement = $this -> user::getAchievementServiceInstance() -> findFirstById($user['user_id']);
    if($resUserAchievement['code'] != 0) { return $this -> _returnScript($resUserAchievement['message']); }

    $resUserTeam = $this -> user::getTeamServiceInstance() -> findFirstById($user['user_id']);
    if($resUserTeam['code'] != 0) { return $this -> _returnScript($resUserTeam['message']); }

    $countTeams = [];
    foreach($resUserTeam['model'] -> team as $k => $lt) {
      $resUser = $this -> user::getServiceInstance() -> findFirst(['conditions' => 'user_id = ' . $k, 'columns' => 'node_side']);
      if($resUser['code'] != 0) { continue; }

      foreach($lt as $ct) {
        if(!isset($countTeams[$resUser['model'] -> node_side])) {
          $countTeams[$resUser['model'] -> node_side] = 1;
        }
        $countTeams[$resUser['model'] -> node_side] += count($ct);
      }
    }

    $countTeams[1] = isset($countTeams[1])?$countTeams[1]:0;
    $countTeams[2] = isset($countTeams[2])?$countTeams[2]:0;

    $this -> view -> setVars([
      'user' => $user,
      'userWallet' => $resUserWallet['model'],
      'userAchievement' => $resUserAchievement['model'],
      'countTeams' => $countTeams,
      'USER_EVERY_ONE_ACHIEVEMENT' => $this -> getParameter('USER_EVERY_ONE_ACHIEVEMENT')
    ]);
  }
}
?>